package net.mcreator.mcreatordetector.config;

import me.shedaniel.autoconfig.AutoConfig;
import me.shedaniel.clothconfig2.api.ConfigBuilder;
import net.mcreator.mcreatordetector.procedures.DisableModProcedure;
import net.mcreator.mcreatordetector.procedures.GetAllMCRModProcedure;
import net.mcreator.mcreatordetector.procedures.RegistryConfigProcedure;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.neoforged.fml.ModList;

public class GetConfigScreen{
    public static Screen getConfigScreen(Screen parent){
        var builder = ConfigBuilder.create();
        builder.setTitle(Component.translatable("config.mcr_detector.title"));
        builder.setParentScreen(parent);
        var category = builder.getOrCreateCategory(Component.empty());
        var entryBuilder = builder.entryBuilder();
        category.addEntry(entryBuilder.startBooleanToggle(Component.translatable("config.mcr_detector.enable"),
                RegistryConfigProcedure.CONFIG.isEnable).setDefaultValue(true)
                .setSaveConsumer(aBoolean -> RegistryConfigProcedure.CONFIG.isEnable = aBoolean).build());
        var modList = GetAllMCRModProcedure.execute();
        if(modList.isEmpty()){
            category.addEntry(entryBuilder.startTextDescription(Component.translatable("config.mcr_detector.empty")).build());
        }else{
            var mcrMods = entryBuilder.startSubCategory(Component.translatable("config.mcr_detector.mods",
                    modList.size()));

            for(String id: modList){
                var m = ModList.get().getModFileById(id);
                if(m == null){continue;}
                var mods = m.getMods();
                if(mods.isEmpty()){continue;}
                var n = mods.getFirst().getDisplayName();
                if(n == null){n = id;}
                mcrMods.add(entryBuilder.startBooleanToggle(
                                Component.literal(n),
                                true
                        ).setDefaultValue(true).setSaveConsumer((b) -> {
                            if(!b){DisableModProcedure.execute(m);}
                        }).setYesNoTextSupplier(aBoolean ->
                                Component.translatable(aBoolean ? "config.mcr_detector.mod.enable":
                                        "config.mcr_detector.mod.disable"))
                        .requireRestart()
                        .build());
            }

            category.addEntry(mcrMods.build());
        }
        builder.setSavingRunnable(() -> {
            AutoConfig.getConfigHolder(ModConfig.class).setConfig(RegistryConfigProcedure.CONFIG);
            AutoConfig.getConfigHolder(ModConfig.class).save();
        });
        return builder.build();
    }
}
